<template>
  <div class='login'>
    <header>
      <header-c></header-c>
    </header>
    <div class="content">
      <div class="left">
        <h2>欢迎您来到我们的世界</h2>
      </div>
      <div class="right">
        <nav class="nav">
          <ul>
            <li v-for="item in navlist" :key="item['id']" :class="{
              'okli': item['id'] === oknavlistRef
            }" @click="navlistF(item['id'])"> {{item.name}} </li>
          </ul>
        </nav>
        <!-- 登录 -->
        <div class="one" v-show="oknavlistRef === 0">
          <div class="one-li">
            <span>账号</span>
            <el-input class="ipt" v-model="loginmsg.username" @keyup.enter="loginBtn" onkeyup="this.value=this.value.replace(/[^\w_]/g,'');"></el-input>
          </div>
          <div class="one-li">
            <span>密码</span>
            <el-input class="ipt" v-model="loginmsg.password" type="password" @keyup.enter="loginBtn"></el-input>
          </div>
          <div style="text-align:center;">
            <el-button class="btn" @click="loginBtn">登录</el-button>
          </div>
        </div>
        <!-- 注册 -->
        <div class="one" v-show="oknavlistRef === 1">
          <div class="one-li">
            <el-input class="ipt" onkeyup="this.value=this.value.replace(/[^\w_]/g,'');"  @keyup.enter="registerBtnF" placeholder="创建账号" v-model="unLoginMessage.username"></el-input>
          </div>
          <div class="one-li">
            <el-input class="ipt" type="password" placeholder="创建密码" v-model="unLoginMessage.password"  @keyup.enter="registerBtnF"></el-input>
          </div>
          <div class="one-li">
            <el-input class="ipt" type="password" placeholder="再次输入密码" v-model="unLoginMessage.alginpassword"  @keyup.enter="registerBtnF"></el-input>
          </div>
          <div style="text-align:center;">
            <el-button class="btn" @click="registerBtnF">注册</el-button>
          </div>
        </div>
      </div>
    </div>
    <!-- 遮罩层 -->
    <div class="shade animate__fadeIn animate__animated" v-if="showShadeRef">
      <div class="card">
        <div>
          <img :src="imgString" class="img" v-if="imgString.length !== 0">
          <div class="img2" v-if="imgString.length === 0">+</div>
          <input type="file" class="file" @change="imgup">
          <div>
            <el-input placeholder="请输入昵称" v-model="unLoginMessage.nickname"></el-input>
          </div>
          <div>
            <el-input placeholder="请输入邮箱" v-model="unLoginMessage.email" @keyup.enter="okBtnF"></el-input>
          </div>
          <div>
            <el-button @click="okBtnF">完成</el-button>
            <el-button @click="calloffbtnF">取消</el-button>
          </div>
        </div>
      </div>
    </div>
  </div>
  
</template>

<script lang='ts'>
import { defineComponent, reactive, ref } from 'vue'
import { ifloginusername, ifStringNull } from '../../tool/ifany'
import { error1, succ1, succ2, warning1 } from '../../tool/ElMessageAny'
// 约束
import {
  Inav,
  TnavlistFun,
  Iloginmsg,
  Tlogins,
  Tnorenocan,
  TboF
  } from './esType'
// 组件
import headerC from '../../components/headerC/index.vue'
// api
import { existUserNameAPI, loginAPI, unloginAPI, upfile64API } from '../../api/userAPI'
import { useRouter } from 'vue-router'

export default defineComponent({
  name: '',
  components: {
    headerC
  },
  setup () {
    // navlist
    const navlist = reactive<Inav[]>([
      {
        id: 0,
        name: '账号密码登录'
      },
      {
        id: 1,
        name: '注册'
      }
    ])
    const oknavlistRef = ref<number>(0)
    const navlistF: TnavlistFun = (id: number) => {
      oknavlistRef.value = id
    }
    // 登录信息 
    const loginmsg = reactive<Iloginmsg>({
      username: '',
      password: ''
    })
    // router路由
    const router = useRouter()
    // const route = useRoute()
    // 登录
    const loginBtn: Tnorenocan = () => {
      if(ifloginusername(loginmsg.username)) {
        warning1('已经登录')
        return;
      }
      logins(loginmsg, 'login')
    }
    const logins: Tlogins = async (loginmsgs: Iloginmsg, me: string) => {
      if(me === 'login') {
        if(ifStringNull(loginmsg.username) || ifStringNull(loginmsg.password)) {
          warning1("填写完整信息后重试")
          return
        }
      }
      try {
        const res = await loginAPI(loginmsgs)
        if(res.data.code === 200) {
          succ2("登录成功")
          window.localStorage.setItem('user', JSON.stringify(res.data.data))
          router.push({
            name: 'my',
            query: {
              userID: res.data.data.id,
              type: 'blog'
            }
          })
          return;
        }
        // 登录出错
        error1(res.data.msg)
      } catch {
        error1('服务器异常')
      }
    }
    // 遮罩层
    const showShadeRef = ref<boolean>(false)
    // 注册信息
    const unLoginMessage = reactive<Iloginmsg>({
      username: '',
      password: '',
      email: '',
      avatar: 'http://www.yswdqz.xyz/wallhaven-72pqze.jpg',
      nickname: '',
      alginpassword: ''
    })
    // 注册按钮
    const registerBtnF: Tnorenocan = async () => {
      if(
        ifStringNull(unLoginMessage.username) ||
        ifStringNull(unLoginMessage.password) ||
        ifStringNull(unLoginMessage.alginpassword)
      ) {
        warning1("请填写完整信息")
        return;
      }
      if(unLoginMessage.username!== undefined && unLoginMessage.password !== undefined) {
        if(unLoginMessage.username.length < 9) {
          warning1('用户名要保持在9位数字以上')
          return
        }
        if(unLoginMessage.password.length < 9) {
          warning1('密码要保持在9位以上')
          return
        }
      }

      if(unLoginMessage.password !== unLoginMessage.alginpassword) {
        warning1("两次密码输入不一致")
        return;
      }
      const res = await usernamealiginF()
      if(!res) {
        return
      }
      showShadeRef.value = true
    }
    // 判断用户名是否重复
    const usernamealiginF = async () => {
      const res = await existUserNameAPI(unLoginMessage.username)
      if(res.data.data) {
        warning1('用户名重复')
        return false
      }
      return true
    }
    // 取消按钮
    const calloffbtnF: Tnorenocan = () => {
      showShadeRef.value = false
    }
    // 判断完成中断
    const emz = /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/
    const ifdun: TboF = () => {
      if(unLoginMessage.email !== undefined) {
        if(!(emz.test(unLoginMessage.email))) {
          error1('邮箱格式错误')
          return false;
        }
      }

      if(ifStringNull(unLoginMessage.avatar) || ifStringNull(unLoginMessage.email) || ifStringNull(unLoginMessage.nickname)) {
        warning1('补全信息后重试')
        return false;
      }
      

      return true
    }
    
    // 完成按钮
    const okBtnF: Tnorenocan = async () => {
      if(!ifdun()) {
        return
      }

      const res = await unloginAPI(unLoginMessage)
      console.log(res);
      if( res.data.code == 400 ) {
        error1(res.data.msg)
      }
      
      if (res.data.code === 200) {

        await logins(unLoginMessage, 'unlogin');
        
      }
    }
    // 上传图片
      // 图片路径
    const imgString = ref<string>('')
    const imgup = async (e: any) => {
      let message1 = e.target.files[0]
      let re = new FileReader()
      re.readAsDataURL(message1)
      re.onload = async () => {
        const res = await upfile64API(re.result)
        if (res.data.code === 200) {
          succ2('更换成功')
          imgString.value = res.data.data
          unLoginMessage.avatar = res.data.data
          console.log(res.data.data)
        } else {
          error1('出错')
        }
      }
    }


    return {
      navlist,
      oknavlistRef,
      navlistF,
      loginmsg,
      logins,
      showShadeRef,
      registerBtnF,
      unLoginMessage,
      okBtnF,
      loginBtn,
      calloffbtnF,
      imgup,
      imgString
    }
  }
})
</script>

<style lang='scss' scoped>
.content{
  height: 600px;
  background-image: url('http://www.yswdqz.xyz/wallhaven-72pqze.jpg');
  background-size: cover;
  display: flex;
  justify-content: center;
  align-items: center;
  .left{
    padding: 40px;
    width: 370px;
    height: 500px;
    background-color: rgba(0,0,0,.4);
  }
  .right{
    padding: 40px;
    width: 500px;
    height: 500px;
    background-color: #fff;
  }
}

.nav{
  ul{
    width: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
    gap: 50px;
    li{
      border-bottom: 1px solid #9f9f9f;
      padding: 8px 10px;
      cursor: pointer !important;
      transition: all 0.1s;
    }
  }
}

.okli{
  border-bottom: 1px solid skyblue !important;
  transform: scale(1.1);
}
.one{
  height: 200px;
  display: flex;
  flex-direction: column;
  justify-content: space-evenly;
  .one-li{
    display: flex;
    align-items: center;
    gap: 5px;
    justify-content: center;
  }
  .ipt{
    width: 300px;
  }
}

.shade{
  width: 100%;
  height: 100%;
  position: absolute;
  top: 0;
  z-index: 99;
  background-color: rgba(0, 0, 0, 0.8);
}
.card{
  width: 400px;
  height: 330px;
  background-color: #fff;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%,-50%);
  text-align: center;
  padding: 20px;
  div{
    margin-bottom: 5px;
  }
}
.img,.img2{
  width: 150px;
  height: 150px;
  margin-bottom: 5px;
}
.img2{
  border: 1px dashed;
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 0 auto;
  font-size: 55px;
  font-weight: 200;
  cursor: pointer;
}
.img2:hover{
  border: 2px dashed skyblue;
}
h2{
  color: #fff;
}
.file{
  background-color: red;
  width: 150px;
  height: 150px;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -96%);
  z-index: 9999;
  opacity: 0;
}
</style>
